﻿using log4net;
using log4net.Config;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

namespace ModbusApp
{
    class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));

        static async Task Main(string[] args)
        {
            XmlConfigurator.Configure(new System.IO.FileInfo("log4net.config"));
            var res =  HslCommunication.Authorization.SetAuthorizationCode("6877ef20-7031-42d2-b5fd-5958a5de9fb5");
            if(res)
            {
                log.Info("auth ok");
            }
            else
                Console.WriteLine("auth Faild");

            // 读取配置文件
            var config = ReadConfig("config.json");

            if (config == null)
            {
                log.Info("配置文件加载失败！");
                return;
            }

            // 用来控制取消线程
            var cancellationTokenSource = new CancellationTokenSource();

            // 存储所有Modbus客户端的任务
            List<Task> clientTasks = new List<Task>();

            // 创建指定数量的客户端并启动线程
            for (byte i = 1; i <= config.DeviceCount; i++)
            {
                var clientHandler = new ModbusClientHandler(config,i);

                if (clientHandler.Connect())
                {
                    log.Info($"客户端 {i + 1} 连接成功");
                    clientTasks.Add(clientHandler.StartWriting(cancellationTokenSource.Token));
                }
                else
                {
                    log.Info($"客户端 {i + 1} 连接失败");
                }
            }

            // 等待用户按任意键取消所有线程
            Console.WriteLine("按任意键停止...");
            Console.ReadKey();
            cancellationTokenSource.Cancel();

            // 等待所有任务结束
            await Task.WhenAll(clientTasks);

            Console.WriteLine("所有任务完成");
        }

        // 读取配置文件
        static Config ReadConfig(string filePath)
        {
            if (!File.Exists(filePath)) return null;

            var jsonString = File.ReadAllText(filePath);
            try
            {
                return JsonSerializer.Deserialize<Config>(jsonString);
            }
            catch
            {
                return null;
            }
        }
    }
}
